//
//  WorkHomeVC.m
//  XLDoctor
//
//  Created by longma on 2018/7/27.
//  Copyright © 2018年 XLH. All rights reserved.
//mj个人资料

#import "PersonalInfoController.h"
#import "SetNameController.h"
#import "UpgradeGoutSchemeView.h"
#import "AppDelegate.h"
#import "HomeController.h"
#import "MJPhotoHelper.h"
#import "MJPickerViewAlertView.h"
#import "MainTabBarViewController.h"

@interface PersonalInfoController ()
@property (weak, nonatomic) IBOutlet MJUICellImageTextView *nicknameItemView;
@property (weak, nonatomic) IBOutlet MJUICellImageBTextView *groupItemView;
@property (weak, nonatomic) IBOutlet MJUICellImageTextView *genderItemView;
@property (weak, nonatomic) IBOutlet MJUICellImageBTextView *birthdateItemView;
@property (weak, nonatomic) IBOutlet MJUICellImageTextView *regionItemView;
@property (weak, nonatomic) IBOutlet MJUIBaseButton *confirmButton;
@property (nonatomic, assign) NSInteger genderType;
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (nonatomic, strong) NSString *headPic;
@property (nonatomic, strong) UIImage *uploadImage;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;

@end

@implementation PersonalInfoController


- (void)viewDidLoad {
    self.backgroundColorType = BackgroundColorTypeGray;

    [super viewDidLoad];
   
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)mj_setUI{
    [super mj_setUI];
    
    self.mj_titleLocalizable = @"My Profile";
    [self setNavRightItemTitle:MJUILocalizedString(@"Skip")];
    self.genderItemView.rightImageView.image = MJUIImageMake(@"icon_shangxiajiantou");
    
    MJWeakSelf
    //手动设置内容得加 RACObserve(self.nicknameItemView.subTitleTextField, text)
    [[RACSignal merge:@[self.nicknameItemView.subTitleTextField.rac_textSignal, RACObserve(self.nicknameItemView.subTitleTextField, text),self.groupItemView.subTitleTextField.rac_textSignal, RACObserve(self.groupItemView.subTitleTextField, text),self.genderItemView.subTitleTextField.rac_textSignal, RACObserve(self.genderItemView.subTitleTextField, text),self.birthdateItemView.subTitleTextField.rac_textSignal, RACObserve(self.birthdateItemView.subTitleTextField, text)]] subscribeNext:^(NSString* text){
        [weakSelf updateUI];
    }];
    self.genderType = -1;
    //
    self.regionItemView.subTitleTextField.text = [HealthHelper getCountryAreaName];
    
    //禁用返回手势 禁止左滑
    self.rt_disableInteractivePop = YES;
    
    self.btnBack.hidden = true;
    self.tipLabel.lineBreakMode = NSLineBreakByWordWrapping;
}

#pragma mark - 方法
- (void)handleRightBarButtonClick {
    MJWeakSelf
    MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
    configure.confirmButtonColor = UIColor.mj_appColor;
    configure.confirmTitle = MJUILocalizedString(@"OK_qd");
    configure.cancelTitle = MJUILocalizedString(@"Cancel_qx");
    configure.messageAlignmentCenter = true;
    NSString *messageString = MJUILocalizedString(@"The information is not saved. Do you really want to exit and discard group member creation?");
    [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Skip Confirmation") message:messageString configure:configure confirmBlock:^{
        
        NSString *userName = UserManager.shared.userModel.phoneNumber ?: UserManager.shared.userModel.email;
        NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:@{
            @"userName":userName ?: @"",
        }];
        
        [MJHttpNetWorking requestWithParams:parms requestUri:user_update requestType:RequestTypePut showLoading:true success:^(MJBaseModel *model) {
            
            if(model.code == 200){
                [UserManager.shared saveUserInfo:model.data];

                AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
                MainTabBarViewController *mainVc = [[MainTabBarViewController alloc]initWithContext:nil];
                appDelegate.window.rootViewController = mainVc;
        //        [appDelegate initRootViewController];
            }

        } failure:^(NSError *error) {
            
        }];

    } cancelBlock:^{

    }];
}

- (void)updateUI {
    BOOL enable = false;
    if(self.nicknameItemView.subTitleTextField.text.length > 0 && self.genderItemView.subTitleTextField.text.length > 0 && self.birthdateItemView.subTitleTextField.text.length > 0){
        enable = true;
    }
    if(enable){
        self.confirmButton.alpha = 1;
    }else{
        self.confirmButton.alpha = 0.5;
    }
}
- (IBAction)handleSaveButtonClick:(UIButton *)sender {
    MJWeakSelf
    if(self.nicknameItemView.subTitleTextField.text.length == 0){
        [RoyHud showToast:MJUILocalizedString(@"Nickname not entered")];
        return;
    }
    if(self.genderItemView.subTitleTextField.text.length == 0){
        [RoyHud showToast:MJUILocalizedString(@"Gender not entered")];
        return;
    }
    if(self.birthdateItemView.subTitleTextField.text.length == 0){
        [RoyHud showToast:MJUILocalizedString(@"Birth date not entered")];
        return;
    }
    if(self.groupItemView.subTitleTextField.text.length == 0){
        MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
        configure.confirmButtonColor = UIColor.mj_appColor;
        configure.confirmTitle = MJUILocalizedString(@"OK_hd");
        configure.cancelTitle = MJUILocalizedString(@"Not Now");
        configure.messageAlignmentCenter = true;
        NSString *messageString = MJUILocalizedString(@"Family or company name not set. Add now?");
        [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Group Name Is Empty") message:messageString configure:configure confirmBlock:^{
            [weakSelf handleGroupButtonClick:nil];
        } cancelBlock:^{
            [weakSelf requestData];

        }];
        return;
    }
    
    [self requestData];
}
- (IBAction)handlePictureButtonClick:(UIButton *)sender {
    MJWeakSelf
    [MJPhotoHelper.shared getSelectPhotoWithBlock:^(UIImage *image) {
        weakSelf.iconImageView.image = image;
        NSLog(@"mj_calulateImageFileSize=======================%@",[image mj_calulateImageFileSize]);
        UIImage *resizeImage = [image mj_resizeImageTargetSize:CGSizeMake(200, 200)];
        UIImage *newImage = [resizeImage mj_compressToSize:120];
        NSLog(@"Size1111=======================%@",[newImage mj_calulateImageFileSize]);
        weakSelf.uploadImage = newImage;

        [weakSelf uploadPhotoWithImage:newImage];
    }];
}
- (void)uploadPhotoWithImage:(UIImage *)image {
    MJWeakSelf
    [MJHttpNetWorking uploadImageWithParams:@{} requestUri:oss_user_headPic image:image showLoading:true success:^(MJBaseModel *model) {
        
        NSLog(@"uploadPhotoWithImage=======================%@",model.data);
        weakSelf.headPic = (NSString *)model.data;
        [MJHttpNetWorking requestWithParams:@{} requestUri:user_update requestType:RequestTypeGet showLoading:false success:^(MJBaseModel *smodel) {
            
            if(smodel.code == 200){
                [UserManager.shared saveUserInfo:smodel.data];
//                [weakSelf updateUI];
            }

        } failure:^(NSError *error) {
            
        }];

    } failure:^(NSError * _Nonnull error) {
        
    }];
}
- (IBAction)handleNicknameButtonClick:(UIButton *)sender {

    MJWeakSelf
    SetNameController *vc = [[SetNameController alloc]init];
    vc.titleItemType = TitleItemTypeNickname;
    vc.text = self.nicknameItemView.subTitleTextField.text;
    vc.handleTitleBlock = ^(NSString *title) {
        weakSelf.nicknameItemView.subTitleTextField.text = title;
    };
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleBirthdateButtonClick:(UIButton *)sender {
    
    MJWeakSelf
    MJPickerViewAlertView *selectDateAlertView = [[MJPickerViewAlertView alloc] init];
    selectDateAlertView.date = self.birthdateItemView.subTitleTextField.text;
    selectDateAlertView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    selectDateAlertView.confirmBlock = ^(NSString *date) {
        weakSelf.birthdateItemView.subTitleTextField.text = date;
    };
    self.modalPresentationStyle = UIModalPresentationCurrentContext;
    [self.navigationController presentViewController:selectDateAlertView animated:NO completion:nil];
}

- (IBAction)handleGroupButtonClick:(UIButton *)sender {
    MJWeakSelf
    SetNameController *vc = [[SetNameController alloc]init];
    vc.titleItemType = TitleItemTypeGroupName;
    vc.text = self.groupItemView.subTitleTextField.text;
    vc.handleTitleBlock = ^(NSString *title) {
        weakSelf.groupItemView.subTitleTextField.text = title;
    };
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleGenderButtonClick:(UIButton *)sender {
    MJWeakSelf
    CGRect targetRect = [self.genderItemView.subTitleTextField convertRect:self.genderItemView.subTitleTextField.bounds toView:self.view];
    UpgradeGoutSchemeView *addVC = [[UpgradeGoutSchemeView alloc] init];
    addVC.targetRect = targetRect;
    addVC.type = self.genderType;
    addVC.confirmBlock = ^(NSInteger type) {
        weakSelf.genderType = type;
        if(type == 0){
            weakSelf.genderItemView.subTitleTextField.text = MJUILocalizedString(@"Male");
        }else{
            weakSelf.genderItemView.subTitleTextField.text = MJUILocalizedString(@"Female");
        }
        if(!weakSelf.uploadImage){
            [weakSelf.iconImageView mj_setHeadImageWithURLString:UserManager.shared.userModel.headPic gender:type == 0 ? @"Male":@"Female"];
        }
    };
    
    addVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    self.modalPresentationStyle = UIModalPresentationCurrentContext;
    [self.navigationController presentViewController:addVC animated:NO completion:nil];
}

- (IBAction)handleRegionButtonClick:(UIButton *)sender {
   
}

- (void)requestData{
    
    MJWeakSelf
    NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:@{
        @"userName":self.nicknameItemView.subTitleTextField.text,
        @"gender":self.genderType == 0 ? @"Male":@"Female",
        @"groupName":self.groupItemView.subTitleTextField.text,
        @"area":self.regionItemView.subTitleTextField.text,
        @"birthday":[self.birthdateItemView.subTitleTextField.text stringByAppendingString:@"-01"],
    }];
    
    [MJHttpNetWorking requestWithParams:parms requestUri:user_update requestType:RequestTypePut showLoading:true success:^(MJBaseModel *model) {
        
        if(model.code == 200){
            //创建用户作为成员
            NSMutableDictionary *patientParms = [NSMutableDictionary dictionaryWithDictionary:@{
                @"patientName":parms[@"userName"],
                @"gender":weakSelf.genderType == 0 ? @"Male":@"Female",
                @"birthday":parms[@"birthday"],
            }];
            if(weakSelf.headPic.length){
                [patientParms setObject:weakSelf.headPic forKey:@"headPic"];
            }
            
            [MJHttpNetWorking requestWithParams:patientParms requestUri:patient_select requestType:RequestTypePost showLoading:true success:^(MJBaseModel *pModel) {
                
                if(pModel.code == 200){
                    
                    [UserManager.shared saveUserInfo:model.data];
                    AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
                    [appDelegate initRootViewController];
                }
                
            } failure:^(NSError *error) {
                
            }];
        }

    } failure:^(NSError *error) {
        
    }];

}

#pragma mark - 代理

#pragma mark - 懒加载

@end
